package com.hll.javaee.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class HelloServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // servletContext可以共享数据, 一个web app中所有servlet 共享一个context,是一种全局上下文环境
    ServletContext servletContext = this.getServletContext();
    String name = "哈哈";
    servletContext.setAttribute("name", name); // 存放key value

    System.out.println(servletContext.getInitParameter("url")); // 获取web.xml context参数

    // 读取properties文件
    InputStream resourceAsStream =
        servletContext
            .getClassLoader()
            .getResourceAsStream("jdbc.properties"); // classloader 是class文件的诸多信息,
    // 项目编译后resources文件夹下的东西都跟class放一起，所以classloader能知道能直接通过文件名查找
    Properties properties = new Properties();
    properties.load(resourceAsStream);
    System.out.println(properties.getProperty("password"));
  }
}
